<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use think\facade\{Db, Cache};
use think\Request;

class ExpressProfitConfigController extends BaseController
{
    /**
     * 获取快递利润配置列表
     */
    public function index()
    {
        $list = Db::name('express_company')
            ->field('id, company_name, company_code, profit_rate, create_time')
            ->select();
            
        return $this->success('获取成功', $list);
    }
    
    /**
     * 设置快递利润配置
     */
    public function save(Request $request)
    {
        $data = $this->validate($request->post(), [
            'id' => 'require|integer',
            'profit_rate' => 'require|float|between:0,100' // 利润率0-100%
        ]);
        
        Db::startTrans();
        try {
            // 检查快递公司
            $company = Db::name('express_company')
                ->where('id', $data['id'])
                ->find();
            if (!$company) {
                throw new \Exception('快递公司不存在');
            }
            
            // 更新利润率
            Db::name('express_company')
                ->where('id', $data['id'])
                ->update([
                    'profit_rate' => $data['profit_rate'],
                    'update_time' => date('Y-m-d H:i:s')
                ]);
            
            // 清除缓存
            Cache::tag('express_profit')->clear();
            
            Db::commit();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
} 